<?php
namespace app\live\controller;

use app\common\model\live\RoomModel;
use helper\Qrcode;
use think\facade\Cache;
use think\facade\Cookie;

class PublicController extends BaseController
{
  protected $model;

  /**
   * 初始化
   */
  public function __construct()
  {
    parent::__construct();
    $this->model = new RoomModel();
  }

  /**直播房间登录
   * type host 主持人 guests嘉宾 assistant助理
   * @return string
   * @throws \Exception
   */
  public function login(){
    if ($this->request->isAjax()) {
      $data = $this->request->param();
      $this->validate($data,[
          'room_id'=>'require',
          'type'=>'require',
          'password|密码'=>'require',
      ]);
      $user = $this->model->login($data['room_id'],$data['nick'],$data['password'],$data['type']);
      //添加在线用户
      D('live.Online')->add([
          'room_id'=>$user['room_id'],
          'user_id'=>$user['userId'],
          'nick'=>$user['nick'],
          'avatar'=>$user['avatar'],
          'role'=>$user['identity'],
      ]);
      Cookie::set('anchor_login',$this->model->setToken($user));
      if($data['type']=='host'){
        $roomInfo = $this->model->where('room_id',$data['room_id'])->find();
        $mainStream  = "host" . md5_16($data['room_id'] . $roomInfo['host_name']);
        Cache::set($data['room_id'].'_main',$mainStream);
      }
      $this->success('登录成功');
    }
    $roleType = [
        'host'=>'主持人',
        'guests'=>'嘉宾',
        'assistant'=>'助理',
    ];
    $roomId = $this->request->param('room_id');
    $type= $this->request->param('type');
    if(empty($type)) abort(500,'登录角色不正确！');
    if(empty($roomId)) abort(500,'没有找到直播间信息！');
    $roomInfo = $this->model->where('room_id',$roomId)->find();
    if(empty($roomInfo)) abort(500,'没有找到直播间信息！');
    $this->assign('room_info',$roomInfo);
    $this->assign('role_type',$roleType[$type]);
    return $this->fetch();
  }


  /**
   * 出错提示
   * @return string
   * @throws \Exception
   */
  public function wrong(){
    $msg = $this->request->param('msg','非法请求');
    $this->assign('msg',$msg);
    return $this->fetch();
  }

  /**
   * 预览输出视频
   * @return string
   * @throws \Exception
   */
  public function play(){
    $roomId = $this->request->param('room_id');
    $roomInfo = $this->model->where('room_id',$roomId)->find();
    $playUrl = $this->model->getPlayUrl($roomId,$roomInfo['host_name']);
    $this->assign('play_url',$playUrl);
    $this->assign('room_info',$roomInfo);
    return $this->fetch();
  }

  public function qrcode(){
    $text = $this->request->param('text');
    return Qrcode::img(html_out($text));
  }


}